const { Op, where } = require("sequelize");
const sequelize = appRequire('db');
var COS = require('cos-nodejs-sdk-v5');
const moment = require('moment');
const tokenHelper = appRequire('common/tokenHelper');

//const unipush = appRequire('common/unipush/push');
const artPPTModel = appRequire('models/artPPT');
const collectModel = appRequire('models/collect');
const artClassModel = appRequire('models/artClass');
const orderModel = appRequire('models/order');
const downLoadModel = appRequire('models/downLoad');
const userModel = appRequire('models/user');
const brannerModel = appRequire('models/branner');
const pptAdsModel = appRequire('models/pptAds');

const downLoadFun = appRequire('controllers/user/downLoad');
const bgSettingModel = appRequire('models/bgSetting');
const common = appRequire('common/common');
const thisRequest = require('sync-request');

// 导出对象，供其它模块调用
module.exports = {
    list,
    detail,
    preview,
    downLoad,
    nowMonthList,
    getLastDayUpdate,
    totalNum,
    typeList,
    aboutList,
    downLoadList,
    unLockPpt,
    baiduDownLoad
};

//课件的下载列表
async function downLoadList(req, request) {
    let postData = req.body
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let result1 = Common.checkUrl(postData, ['pptId'], request);
    if (result1 == false) return;


    let result2 = await downLoadModel.downLoad.findAll({
        where: {
            artpptId: postData.pptId,
        },
        include: ["user"],
        order: [['createdAt', 'DESC']],
        limit: 40,
    })

    result2 = Common.clone(result2)
    let newArray = []
    for (let item of result2) {
        if (item.user && item.user.objectId) {
            if (item.user.avatarUrl && item.user.avatarUrl && item.user.avatarUrl.indexOf('artppt-1306121076.cos.ap-nanjing.myqcloud.com') != -1) {
                item.user.avatarUrl = item.user.avatarUrl + "?imageMogr2/format/WebP"
            }
            newArray.push({
                nickName: item.user.nickName,
                avatarUrl: item.user.avatarUrl,
            })
        }
    }


    returnData.data = newArray
    request.json(returnData)
}

//收录课件总数
async function totalNum(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let course = await artPPTModel.count()
    returnData.data = Common.clone(course)
    request.json(returnData)
}

async function getLastDayUpdate(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let nowDay = postData.nowDay;
    let year = nowDay.split("-")[0]
    let month = nowDay.split("-")[1]
    maxDay = new Date(year, month, 0).getDate()

    let course = await artPPTModel.findAll({
        where: {
            createdAt: {
                [Op.gt]: year + '-' + month + "-01 00:00:00",
                [Op.lt]: year + '-' + month + "-" + maxDay + " 23:59:59"
            },
        },
        attributes: ['createdAt'],
    })
    course = Common.clone(course)

    let newRes = []

    for (let item of course) {
        item.createdAt = dateFormat(item.createdAt, 'yyyy-mm-dd');
        let newResItem = {
            date: item.createdAt,
            info: 0,
            dropColor: '#ff8080',
            fontColor: '#ff8080',
        }
        //newResItem.date = item.createdAt
        let thisIndex = newRes.findIndex(newItem => newItem.date == item.createdAt)
        if (thisIndex == -1) {
            newRes.push(newResItem)
        } else {
            newRes[thisIndex].info += 1
        }
    }

    returnData.data = newRes
    request.json(returnData)
}

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {
        status: 1
    }
    let orders = [['isNice', 'DESC'], ['downLoadNum', 'DESC'], ['createdAt', 'DESC']]
    //if (postData.classId) params.ClassId = postData.classId
    if (postData.TypeId) params.TypeId = postData.TypeId
    if (postData.order) {
        if (postData.order.indexOf("-") == -1) {
            orders = [[postData.order, 'ASC']]
        } else {
            orders = [[postData.order.split("-")[1], 'DESC']]
        }
    }

    if (postData.searchText) {
        params[Op.or] = [
            { title: { [Op.like]: '%' + postData.searchText + '%' } },
            { desc: { [Op.like]: '%' + postData.searchText + '%' } },
            { tags: { [Op.substring]: '%' + postData.searchText + '%' } },
            { fileUrls: { [Op.substring]: '%' + postData.searchText + '%' } },
        ]
    } else {
        params.sourceFrom = { [Op.not]: ["创意少儿美术馆", "指尖美术", "指间美术"] }
    }

    if (postData.fileType) {
        params.fileType = postData.fileType
    } else {
        params.fileType = { [Op.ne]: "书法" }
    }
    if (postData.classDesc && postData.classId) {
        params.classDesc = {}
        params.classDesc[Op.and] = [] //{ [Op.ne]: '课程' }
        params.classDesc[Op.and].push({ [Op.substring]: '%' + postData.classDesc + '%' })
    }
    if (postData.age) {
        params.ageMin = { [Op.lte]: postData.age }
        params.ageMax = { [Op.gte]: postData.age }
    }
    if (postData.nowDay) {
        params.createdAt = {
            [Op.gt]: postData.nowDay + " 00:00:00",
            [Op.lt]: postData.nowDay + " 23:59:59"
        }
    }

    if (postData.isNice) params.isNice = postData.isNice
    if (postData.TypeId) params.TypeId = postData.TypeId
    if (postData.userId) params.userId = postData.userId
    if (postData.isFree) {
        let zt = moment().format('YYYY-MM-DD')
        params.price = { [Op.eq]: 0 }
        params.updatedAt = {
            [Op.gt]: zt + " 00:00:00",
            [Op.lt]: zt + " 23:59:59"
        }
    }

    //if (postData.fileType) params.fileType = postData.fileType

    // 构建 include 数组
    let includeArray = ["typeDesc"]

    // 如果查询课程列表，附加关联查询前8个课件
    if (postData.fileType === '课程') {
        includeArray.push({
            model: artPPTModel,
            as: 'coursewares',
            where: {
                status: 1
            },
            attributes: ['objectId', 'title', 'images', 'desc', 'dominantColor', 'dominantColor2'],
            limit: 8,
            order: [['createdAt', 'DESC']],
            required: false, // LEFT JOIN，即使没有课件也返回课程
            separate: true, // 分开查询，解决 limit 不生效的问题
        })
    }

    let course = await artPPTModel.findAndCountAll({
        where: params,
        order: orders,
        limit: postData.pageSize,
        offset: postData.pageSize * (postData.pageNum - 1),
        include: includeArray,
        attributes: ["isBaiduFile", "courceNumber", "getType", "images", "title", "tags", "isNew", "age", "objectId", "type", "fileType", "fileUrls", "ageMax", "ageMin", "price", "downLoadNum", "classDesc", "baiduDeskLink", "dominantColor", "dominantColor2"],
    })
    course = common.clone(course)
    course.rows = await common.transfromDataList(course.rows)

    for (let item of course.rows) {
        if (!item.courceNumber) {
            let newimages = []
            if (item.images && item.images.length > 0) {
                for (let thisImage of item.images) {
                    thisImage = thisImage.split("?imageMogr2/format/WebP")[0]
                    if (thisImage.indexOf("/sf") == -1) {
                        thisImage = thisImage + "/sf"
                    }
                    newimages.push(thisImage)
                }
                item.images = newimages
            }
        }

        // 如果是课程且有关联的课件，合并课件的 images 到课程的 images 中
        if (item.coursewares && item.coursewares.length > 0) {
            for (let courseware of item.coursewares) {
                if (courseware.images && courseware.images.length > 0) {
                    // 将课件的 images 合并到课程的 images 数组中
                    item.images = item.images.concat(courseware.images)
                }
            }
            // 删除 coursewares 字段
            delete item.coursewares
        }
    }

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}

//相关推荐
async function aboutList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {
        status: true
    }
    let orders = [['isNice', 'DESC'], ['downLoadNum', 'DESC'], ['createdAt', 'DESC']]
    params[Op.or] = []
    if (postData.tags) {
        for (let tag of postData.tags) {
            params[Op.or].push({ tags: { [Op.substring]: '%' + tag + '%' } })
            params[Op.or].push({ desc: { [Op.substring]: '%' + tag + '%' } })
            params[Op.or].push({ tags: { [Op.substring]: '%' + tag + '%' } })
            params[Op.or].push({ fileUrls: { [Op.substring]: '%' + tag + '%' } })
        }
    }
    if (postData.TypeId) params[Op.or].push({ TypeId: postData.TypeId });
    params.sourceFrom = { [Op.not]: ["创意少儿美术馆", "指尖美术", "指间美术"] }
    let course = await artPPTModel.findAndCountAll({
        where: params,
        order: orders,
        limit: 20,
        //offset: postData.pageSize * (postData.pageNum - 1),
        include: ["typeDesc"],
        attributes: ["images", "title", "tags", "isNew", "age", "objectId", "type", "fileType", "fileUrls", "ageMax", "ageMin", "price", "downLoadNum", "classDesc", "dominantColor", "dominantColor2"],
    })
    course = Common.clone(course)
    course.rows = await common.transfromDataList(course.rows)

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}

//当前精选内容
async function nowMonthList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {
        isNice: true
    }

    //console.log(year, month, maxDay)
    let course = await artPPTModel.findAndCountAll({
        where: params,
        order: [['createdAt', 'DESC']],
        attributes: ["images", "title", "tags", "isNew", "age", "objectId", "classDesc"],
        limit: 20
    })
    course = Common.clone(course)
    course.rows = Common.transfromDataList(course.rows)

    returnData.maxCount = course.count
    returnData.maxPage = Math.ceil(course.count / postData.pageSize)
    returnData.data = course.rows
    request.json(returnData)
}

//专题内容
async function typeList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {
        isShow: true,
    }
    let course = await artClassModel.artType.findAll({
        where: params,
        order: [['createdAt', 'DESC']],

        include: [{
            where: {
                status: true
            },
            model: artPPTModel,
            as: 'typeList',
            attributes: ["images", "title", "tags", "isNew", "age", "objectId", "type", "fileType", "fileUrls", "ageMax", "ageMin", "price", "downLoadNum", "classDesc", "baiduDeskLink", "dominantColor", "dominantColor2"],
        }]
    })

    course = Common.clone(course)
    for (let item of course) {
        let typeImages = []
        for (let image of item.images) {
            typeImages.push(image + "?imageMogr2/format/webp")
        }
        if (item.typeList.length > 10) item.isMore = true
        item.typeList = item.typeList.slice(0, 14)
        item.typeList = Common.transfromDataList(item.typeList)
        item.typeImages = typeImages
    }

    returnData.data = course
    request.json(returnData)
}

//ppt详情
async function detail(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    // 构建 include 数组
    let includeArray = ["user"]

    // 先查询判断是否是课程
    let tempCourse = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        },
        attributes: ['classDesc', 'fileType']
    })

    // 如果是课程，附加查询所有关联的课件
    if (tempCourse && (tempCourse.classDesc === '课程' || tempCourse.fileType === '课程')) {
        includeArray.push({
            model: artPPTModel,
            as: 'coursewares',
            where: {
                status: 1
            },
            attributes: ['objectId', 'title', 'images', 'desc', 'price', 'downLoadNum', 'dominantColor', 'dominantColor2'],
            order: [['createdAt', 'DESC']],
            required: false,
            separate: true,
        })
    }

    let course = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        },
        include: includeArray
    })
    course = Common.clone(course)
    course.collect = 0

    if (postData.uid) { //登陆获取是否收藏
        result2 = await collectModel.collect.findOne({
            where: {
                artpptId: course.objectId,
                userId: postData.uid,
            },
        })
        if (result2) course.collect = 1

        //价格不是0的时候是否解锁
        course.isLock = false
        let thisUser = await userModel.user.findOne({
            where: {
                objectId: postData.uid
            }
        })
        thisUser = Common.clone(thisUser)
        if (thisUser && thisUser.vipTime) { //已是会员
            course.isLock = true
        } else {
            result4 = await orderModel.order.findOne({
                where: {
                    status: 1,
                    buyerId: postData.uid,
                    pptId: course.objectId,
                }
            })
            if (result4 || postData.uid == course.userId) course.isLock = true
        }

        if (!course.isLock) {
            let nowDay = dateFormat(new Date().getTime(), 'yyyy-mm-dd')

            let todayBranner = await brannerModel.todayBranner.findOne({
                where: {
                    time: nowDay + " 08:00:00",
                    artpptId: postData.objectId
                },
            })
            if (todayBranner) course.isLock = true
        }
    }

    if (course.type == "单个" && !course.isNew) {
        course.size = course.size || 0
        if (course.fileUrls && course.fileUrls[0]) course.size = course.fileUrls[0].size
    }

    if (course.user && course.user.objectId) {
        course.userName = course.user.nickName
        course.userAvatarUrl = course.user.avatarUrl
        delete course.user
    }

    //图片根据页数生成
    for (let item of course.fileUrls) {
        if (course.fileType == "课件") {
            if (course.images && course.images.length > 0) {
                for (let img of course.images) {
                    if (img.indexOf('imageMogr2/format/WebP') == -1) img = img + '?imageMogr2/format/WebP'
                }
            } else {
                item.page = item.page || 1
                for (let i = 1; i <= item.page; i++) {
                    course.images.push(item.fileUrl + '?ci-process=doc-preview&dstType=png&page=' + i + '&scale=40&imageMogr2/format/WebP')
                }
            }
        } else if (course.fileType == "素材") {
            course.images.push(item.fileUrl + '/sf')
        }
    }

    delete course.pptUrl
    delete course.baiduDeskImage
    delete course.baiduDeskLink

    if (course.isNew && course.images.length > 0) {
        if (course.images[0].indexOf("ci-process=doc-preview&dstType=png") == -1) {
            course.backgroundImage = course.images[0].split('?imageMogr2/format/WebP')[0] + "/small"
        }
    }

    // coursewares 已通过 include 自动获取，无需手动查询
    // 如果有 coursewares，转换为数组格式
    if (course.coursewares) {
        course.coursewares = Common.clone(course.coursewares)
    }

    returnData.data = course
    returnData.data.ids1 = Common.getIds(postData.source, "longSmall")
    returnData.data.ids2 = Common.getIds(postData.source, "pptDetail")
    returnData.data.ids3 = Common.getIds(postData.source, "jlsp")
    request.json(returnData)
}

//百度网盘文件下载
async function baiduDownLoad(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;
    let course = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)
    course.isLock = false

    //是否解锁
    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.uid
        }
    })
    thisUser = Common.clone(thisUser)
    if (thisUser && thisUser.vipTime) { //已是会员
        course.isLock = true
    } else {
        let thisOrderParams = {
            status: 1,
            buyerId: postData.uid,
            pptId: course.objectId
        }
        result4 = await orderModel.order.findOne({
            where: thisOrderParams
        })
        if (result4) course.isLock = true
    }

    if (course.isLock == false) {
        returnData.code = 101
        returnData.data = false
        returnData.msg = "该课件需要付费后解锁下载"
        return request.json(returnData)
    }

    url = "https://pan.baidu.com/share/set?channel=chunlei&bdstoken=b97f52c9cbed9a4d422d7ffc2016675a&clienttype=0&app_id=250528&web=1&dp-logid=51394400511602950158&fid_list=[" + course.fs_id + "]&schannel=4&pwd=1090&period=1"

    var res = thisRequest('POST', url, {
        json: {},
        headers: {
            'User-Agent': 'pan.baidu.com',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie':'BIDUPSID=55196A6BCB5C89068658CB3F9A8CFC00; PSTM=1740896675; MAWEBCUID=web_zJJJZpZrXOOWsNuVIZDlVwSCqrLZZFCuBPqqcmIqkVLCdTZppr; PANWEB=1; newlogin=1; Hm_lvt_fa0277816200010a74ab7d2895df481b=1756040271; Hm_lvt_7a3960b6f067eb0085b7f96ff5e660b0=1758622795,1759152746,1760491552,1760593997; BDCLND=a9HgjOhmBgFCqS6Hn5RIOvtHosbbUQxVa19YhyxhHaQ%3D; H_WISE_SIDS_BFESS=63148_64004_65248_65361_65759_65772_65864_65893_65857_65912_65918_65937_65943_65968_65956_65989_65992_66084_66102_66111_66142_66210_66218; ZFY=fjislOcn8Ybdfl8fpUei:AoK1AShHHThFAXySJO:BjUL8:C; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; arialoadData=false; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; PSINO=3; delPer=0; csrfToken=vcMndsyAdC5q3p3yMustfzSZ; Hm_lvt_95fc87a381fad8fcb37d76ac51fefcea=1762686498; HMACCOUNT=F7DEFA85EE7A310F; log_chanel=seo_qadetail; log_first_time=1762686985215; __bid_n=196e2eb878d6416c697ae9; log_last_time=1762686995599; Hm_lpvt_95fc87a381fad8fcb37d76ac51fefcea=1762687703; Hm_lvt_182d6d59474cf78db37e0b2248640ea5=1762413839,1762605310,1762623510,1762688238; Hm_lvt_0ba7bcf57b5e55fbfbab9a2750acdf3e=1762496556,1762663017,1762697878; Hm_lpvt_0ba7bcf57b5e55fbfbab9a2750acdf3e=1762697923; BAIDUID=CF7941BF67482FA4ACBF2E363B7079D2:FG=1; BAIDUID_BFESS=CF7941BF67482FA4ACBF2E363B7079D2:FG=1; H_PS_PSSID=60278_63148_65246_65313_65361_65592_65611_65759_65797_65862_65915_65918_65930_65963_65986_66011_66075_66121_66131_65864_66221_66195_66293_66330_66361_66344_66372; BA_HECTOR=040h81208k2g0h0k80858ka5802gak1kh19e825; H_WISE_SIDS=60278_63148_65246_65313_65361_65592_65611_65759_65797_65862_65915_65918_65930_65963_65986_66011_66075_66121_66131_65864_66221_66195_66293_66330_66361_66344_66372; BCLID=10862879381695981146; BCLID_BFESS=10862879381695981146; BDSFRCVID=o0_OJexroGWxYDnELWzWheLMnmKKe4oTDYLEOwXPsp3LGJLVzaaQEG0Pts1-dEub6j3eogKKL2OTHRKF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; BDSFRCVID_BFESS=o0_OJexroGWxYDnELWzWheLMnmKKe4oTDYLEOwXPsp3LGJLVzaaQEG0Pts1-dEub6j3eogKKL2OTHRKF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tbC8VCDKJDD3H48k-4QEbbQH-UnLq-4jX2OZ04n-ah3RJMTehxod3nIiMMorW46LW23-_n7m3UTdsq76Wh35K5tTQP6rLJTKKG64KKJxbP8aKJbH5tK-M6t8hUJiBMAHBan7bqvIXKohJh7FM4tW3J0ZyxomtfQxtNRJ0DnjtpChbRO4-TFbDTj03f; H_BDCLCKID_SF_BFESS=tbC8VCDKJDD3H48k-4QEbbQH-UnLq-4jX2OZ04n-ah3RJMTehxod3nIiMMorW46LW23-_n7m3UTdsq76Wh35K5tTQP6rLJTKKG64KKJxbP8aKJbH5tK-M6t8hUJiBMAHBan7bqvIXKohJh7FM4tW3J0ZyxomtfQxtNRJ0DnjtpChbRO4-TFbDTj03f; ppfuid=FOCoIC3q5fKa8fgJnwzbE0LGziLN3VHbX8wfShDP6RCsfXQp/69CStRUAcn/QmhIlFDxPrAc/s5tJmCocrihdwitHd04Lvs3Nfz26Zt2holplnIKVacidp8Sue4dMTyfg65BJnOFhn1HthtSiwtygiD7piS4vjG/W9dLb1VAdqN/BwMntIdwfP0PEb9nt0GfO0V6uxgO+hV7+7wZFfXG0MSpuMmh7GsZ4C7fF/kTgmsJHOGPfUa6yy9yRfFY41Ww2GccuiUrH23KtKzZ3L3CgpHrMnmNS0BuXxFIC2LBAKk1v2iwj13daM+9aWJ5GJCQM+RpBohGNhMcqCHhVhtXpVObaDCHgWJZH3ZrTGYHmi7XJB9z3y2o8Kqxep5XBCsugNOW5C73e/g54kuY4PKIS43fV9OTtk//OSSNzeKuX0aZEel5w7RlX7adSxhJ1HARnvNXIEW2pwj4BXINSNFrPACWH6JM+J+dYFX/7UmLGRgFMb7+JFWxNGoA0JNiv6hCb0gkXpkEpISi6tVHh+hsQifjACGGz0MbLI9AAutvQNmLovQE8DrrUkOPSWZkiBwIUvxonSGS2lgiNZBxgK/Nad6P3sfvyvYhyXNwxm6SzH+Oja1l6cy9uoP7y446ILa1CLEOaV1jDkGoksNhRtn7B1VPovN1TRU04qLrmECuDGMBVR4vlhy8DqZQ1/LUEQ9mjyqP/SnZsRdyLAjuA3ESTcrCSmS6iWcmxBDT8gjuTbf5rG4+h0gsZ2eMGgzIHtuSt0U1CdMITVnbWw408saXqYrhBzluVsCC9UwFS6D3ctFGODZQIh4W3MDTacL/DY1Q8YClTpPkuiWM0gZm41VCO+dj8pAfyVHqnsedsJI6TBFIvNOHWlA4ALxNVt7DVMwSa2bzqsCqzf6y1nB7JA6BQ6B5CJ7l2SqRfD3rNamTW9YiSlWezhT+jZD8JrX33/HNMM0aOdAredMfLeYMj+uN0MK5mpzYSmDsgYAGcZbGmnun8qe7C/Z6wAh6Sxpet2o2XdT5gjozQON5/HVPvKJVz/HEk0MlL4OWxuq7efgjrm7u8eNg3xj0WwQipSI+BocHNo9YRuQO2pi4iArzUvik/DxSHbvZCfaziGZggaG+BY2OEydWPa1CZLO/GyxE2lrKfp8o7MtQH8zZ7JAK2DmuATYE6knbkS7/y5uZBK5lY9wL+toPXRBoL0qepeNu3r3x; bce-sessionid=001b73053664bf549218aa428cfcabc36cc; RT="z=1&dm=baidu.com&si=c5f0fab6-2e78-4d0c-8639-95dd2e62933b&ss=mhrtbdne&sl=c&tt=d7o&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=8mxx&nu=1629zljr&cl=8oih&ul=8om4&hd=8op3"; ploganondeg=1; XFI=bf5639f0-bd83-11f0-8a81-092a6ede0608; XFCS=9743B9454D285DA26A3E1ECD07205D7814ED95C3E537AED822D6220E17885CF6; XFT=xzAcddt2pddPIm5UEoy9VAJn9tIXEjE8g7jiSnZFdXI=; BDUSS=UtUHdHcUdlM1FOMEx-NDd0aGtwQUZkT2h3eEN4M3RoeDJYVEZOY1VsTS1SVGhwSUFBQUFBJCQAAAAAAAAAAAEAAAB0NWk6w8DK9dTG1vrK1gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD64EGk-uBBpfj; BDUSS_BFESS=UtUHdHcUdlM1FOMEx-NDd0aGtwQUZkT2h3eEN4M3RoeDJYVEZOY1VsTS1SVGhwSUFBQUFBJCQAAAAAAAAAAAEAAAB0NWk6w8DK9dTG1vrK1gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD64EGk-uBBpfj; STOKEN=09f04364f441f2be84cc1220c386c487b3590e9dfe24066b7e526d354aab45d0; Hm_lpvt_182d6d59474cf78db37e0b2248640ea5=1762703424; ndut_fmt=7BD2E0E0BC9773B8C5F4D8E69ABDC69729BE68EE0CE56D499DB1C143D92BC4F2; ab_sr=1.0.1_Y2EzMzQ3MWIzYTA0NGU2YzVjYmY5NGQ3MDQ1ZWJlYmRmNzkyMzg5OTIzNWNiZDVlZDc4YzA5MDIzM2MyNTRjZTJjM2M2M2IyOWE0Zjk1ZGM4MjQ5MzBjMDc4MjAyMzJmNWJlZTNhYjNkNjJmZTdmNzNiMTQzMWFhMzJiMTI3MjBkYTcwNzJmNzE2MjIzMjA3MjA2YjM2NWM1YWJhZGE2ZjA0NzI3ZGVkNmMzMGI3N2NhMWZjYmMyNmUyMzE1MmU4; PANPSC=3669665682734009542%3Au9Rut0jYI4r%2BolUN3fmDkVcS2d9ns3O5C61tf8CKQkjD7mIyb5eXfHPc7e%2BR5fDLS2iRyBmo4yTzv1VCKn0pR%2BNHiOwr%2ByPWC%2BYWBHXUXSu2ddnuR8GWusdco%2Fbt7h4BNjEwWb60Ojg2jyb7JodIirvtbMLU%2FJYsuvcMP1zPO9dAnA13%2BASJnKiEhIPF2zzulxEjsSl24iFipl3L3NnXeWx9nzu7xbIv9ISIoyMqZV348JnwKQPF%2B%2BW2uSjJMm6ru0hOEHdvreXGHdpmVJME2SrIg40OsQ29yBKO1nu%2B7jwrXEkz08ru1FDNWDfQpqapDBj9GKJIwjpouYqxfDzDciSq0Nvr47VTkrFWWqsgPEw%3D'
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容

    //console.log(jsonObj)

    if (jsonObj) {
        jsonObj.baiduDeskLink = jsonObj.link
        let thisWords = jsonObj.link.split("https://pan.baidu.com/s/")
        let shortUrl = thisWords[1].replace("?", "&")
        jsonObj.baiduDeskImage = "https://pan.baidu.com/api/wechat/qrcode?width=150&clienttype=0&shorturl=" + shortUrl
        returnData.data = jsonObj
    }
    return request.json(returnData)
}

//单个文件下载
async function downLoad(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    // 从数据库获取百度网盘token
    const access_token = await tokenHelper.getBaiduToken();

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    // iOS 功能检查（从系统配置读取）
    if (postData.source && (postData.source === 'ios' || postData.source.indexOf('ios') !== -1)) {
        const iosCanIn = await tokenHelper.getIosCanIn();
        if (iosCanIn === '0') {
            returnData.code = 0;
            returnData.msg = "由于相关规范，iOS功能暂不可用";
            return request.json(returnData);
        }
    }

    let course = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)
    course.isLock = false
    //是否解锁
    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.uid
        }
    })
    thisUser = Common.clone(thisUser)
    if (thisUser && thisUser.vipTime) { //已是会员
        course.isLock = true
    }  else {
        let thisOrderParams = {
            status: 1,
            buyerId: postData.uid,
            pptId: course.objectId
        }
        result4 = await orderModel.order.findOne({
            where: thisOrderParams
        })
        if (result4) course.isLock = true
    }

    if (course.status == false) {
        returnData.code = 0
        returnData.msg = "该课件还在审核中"
        return request.json(returnData)
    }

    if (!course.isLock) {
        let nowDay = dateFormat(new Date().getTime(), 'yyyy-mm-dd')

        let todayBranner = await brannerModel.todayBranner.findOne({
            where: {
                time: nowDay + " 08:00:00",
                artpptId: postData.objectId
            },
        })
        if (todayBranner) course.isLock = true
    }

    if (course.isLock == false) {
        returnData.code = 101
        returnData.data = false
        returnData.msg = "该课件需要付费后解锁下载"

        let adNum = await pptAdsModel.findOne({
            where: {
                userId: postData.uid,
                pptId: course.objectId
            }
        })
        adNum = Common.clone(adNum)
        returnData.adNum = 0
        if (adNum) returnData.adNum = adNum.num
        returnData.nadNum = course.adNum - returnData.adNum
        return request.json(returnData)
    }

    if (course.isNew) {
        returnData.data.fileUrls = "未上传文件"
        returnData.data.baiduDeskLink = course.baiduDeskLink
        returnData.data.baiduDeskImage = course.baiduDeskImage

        if (course.isBaiduFile) {
            if (course.baiduDeskLink.indexOf("?pwd=") == -1) {
                course.baiduDeskLink = course.baiduDeskLink + "?pwd=1090"
                returnData.data.baiduDeskLink = course.baiduDeskLink
            }
            if (course && course.fileUrls && course.fileUrls.length > 0) {
                if (course.fileUrls[postData.index] && course.fileUrls[postData.index].fileUrl) {
                    let thisFileUrl = course.fileUrls[postData.index].fileUrl
                    var cos = new COS({
                        SecretId: 'AKIDuc5GAnAG5duuHQJwHL8fusZz80bvykFT',
                        SecretKey: 'zh8IAm7BxSgdJhpgFXZJmzvd5HDrEK9g'
                    });

                    if (thisFileUrl.indexOf("https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/") != -1) {
                        let thisValues = thisFileUrl.split("https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/")
                        thisFileUrl = "https://file.jimuzhou.cloud/" + thisValues[1]
                    }
                    let splitWords1 = thisFileUrl.split("https://file.jimuzhou.cloud")
                    let thisResult = await cos.getObjectUrl({
                        SecretId: 'AKIDuc5GAnAG5duuHQJwHL8fusZz80bvykFT',
                        SecretKey: 'zh8IAm7BxSgdJhpgFXZJmzvd5HDrEK9g',
                        Bucket: 'artppt-1306121076', /* 必须 */
                        Region: 'ap-nanjing',    /* 必须 */
                        Key: splitWords1[1],
                        Domain: "https://file.jimuzhou.cloud",
                        Sign: true,
                        Expires: 300, // 单位秒
                    });
                    returnData.data.fileUrls = thisResult
                }
            } else {
                url = "http://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=" + access_token + "&fsids=[" + course.fs_id + "]&dlink=1&thumb=0"

                var res = thisRequest('GET', url, {
                    headers: {
                        'User-Agent': 'pan.baidu.com'
                    }
                });
                var body = res.getBody();
                var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容

                let detail = jsonObj.list[0]
                returnData.data.fileUrls = detail.dlink
            }
        }

        //加入到我的下载
        let thisBody = Common.clone(req.body)
        thisBody.artpptId = postData.objectId
        await downLoadFun.downLoadService({ body: thisBody })
    } else {
        if (course.classDesc == "课程") {
            returnData.data = course.baiduDeskLink

            //加入到我的下载
            let thisBody = Common.clone(req.body)
            thisBody.artpptId = postData.objectId
            await downLoadFun.downLoadService({ body: thisBody })
        }
    }
    return request.json(returnData)
}

//预览PPt
async function preview(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let course = await artPPTModel.findOne({
        where: {
            objectId: postData.objectId
        },
    })
    course = Common.clone(course)
    if (course && course.fileUrls && course.fileUrls.length > 0) {
        let thisFileUrl = course.fileUrls[postData.index].fileUrl
        var cos = new COS({
            SecretId: 'AKIDuc5GAnAG5duuHQJwHL8fusZz80bvykFT',
            SecretKey: 'zh8IAm7BxSgdJhpgFXZJmzvd5HDrEK9g'
        });

        if (thisFileUrl.indexOf("https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/") != -1) {
            let thisValues = thisFileUrl.split("https://artppt-1306121076.cos.ap-nanjing.myqcloud.com/")
            thisFileUrl = "https://file.jimuzhou.cloud/" + thisValues[1]
        }
        let splitWords1 = thisFileUrl.split("https://file.jimuzhou.cloud")
        let thisResult = await cos.getObjectUrl({
            SecretId: 'AKIDuc5GAnAG5duuHQJwHL8fusZz80bvykFT',
            SecretKey: 'zh8IAm7BxSgdJhpgFXZJmzvd5HDrEK9g',
            Bucket: 'artppt-1306121076', /* 必须 */
            Region: 'ap-nanjing',    /* 必须 */
            Key: splitWords1[1],
            Domain: "https://file.jimuzhou.cloud",
            Sign: true,
            Expires: 300, // 单位秒
        });
        returnData.data = thisResult + '&ci-process=doc-preview&dstType=html'
    } else {
        returnData.code = 0
        returnData.msg = "未上传文件"
    }
    request.json(returnData)
}

async function unLockPpt(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['pptId', 'out_trade_no'], request);
    if (checkResult == false) return;

    let course = await artPPTModel.findOne({
        where: {
            objectId: postData.pptId
        },
    })
    course = Common.clone(course)

    let adNumDetail = await pptAdsModel.findOne({
        where: {
            userId: postData.uid,
            pptId: postData.pptId
        }
    })
    adNumDetail = Common.clone(adNumDetail)
    if (!adNumDetail) {
        await pptAdsModel.create({
            userId: postData.uid,
            pptId: postData.pptId,
            num: 1
        })
    } else {
        adNumDetail = await pptAdsModel.update({
            num: adNumDetail.num + 1
        }, {
            where: {
                userId: postData.uid,
                pptId: postData.pptId
            }
        })
    }
    adNumDetail = await pptAdsModel.findOne({
        where: {
            userId: postData.uid,
            pptId: postData.pptId
        }
    })

    let sAdnum = adNumDetail.num
    if (sAdnum >= course.adNum) {
        let result1 = await orderModel.order.create({
            objectId: sid.uuid(),
            out_trade_no: postData.out_trade_no,
            status: 1,
            pptId: postData.pptId,
            payMoney: 0,
            storeMoney: 0,
            sellerId: course.userId,
            buyerId: postData.uid,
            type: 2,
        })

        returnData.data = result1
    } else {
        returnData.code = 101
        returnData.nadNum = course.adNum - sAdnum
    }
    return request.json(returnData)
}